local BaseWnd = require(SCRIPTS_DIR .. ".wnds.BaseWnd");
local Bullet = require(SCRIPTS_DIR .. ".pubs.Bullet");
local Fish = require(SCRIPTS_DIR .. ".pubs.Fish");
local Player = require(SCRIPTS_DIR .. ".pubs.Player");
local BattleWnd = class("BattleWnd",BaseWnd);
function BattleWnd:ctor()
	BattleWnd.super.ctor(self);
    self.isTickOnFire = false;
    self.scheduleLongClick = 0;
    self.longClickTime = 0;
    self.frameCbk = nil;
end

function BattleWnd:onOpen()
    mgrs.input:lock(enums.Locker.NoPlayerEnter);
    self.playerNums = self.wndData.param.num;
    self.battleKind = self.wndData.param.kind;
    self.visibleRect = cc.Director:getInstance():getOpenGLView():getVisibleRect();
    self.fishLayer = self:widget("middle.fishLayer");
    self.bulletLayer = self:widget("middle.bulletLayer");
    self.cannonLayer = self:widget("middle.cannonLayer");
    self.scheduleFish = mgrs.scheduler:scheduleGlobal(handler(self,self.updateFish),mgrs.fish:getTickTime());
    --self.scheduleTest = mgrs.scheduler:scheduleGlobal(handler(self,self.updateTest),5);
    self.scheduleBullet = mgrs.scheduler:scheduleUpdateGlobal(handler(self,self.updateBullet));
    self:setTouchEvent();
    self:closeWnd();
    self:setSitePosition();
    self:testAddFish();
    self:setDebug(true);
    self:addSchedulerCbk(handler(self,self.battleFrameEvent),enums.Scheduler.Frame);
end


function BattleWnd:battleFrameEvent()
    local actions = mgrs.data:getBattleData():getActions();
    if table.nums(actions) >= 1 then
        print("1111111111111111111");
        local curFrame = mgrs.data:getBattleData():getCurFrame();
        local doActions = {};
        for key, var in pairs(actions) do
            print(var.eframe,curFrame);
            if var.eframe <= curFrame then
                print("222222222222222222");
                table.insert(doActions,var);
            end
        end
        for key, var in pairs(doActions) do
            self:doFrameAction(var);
        end
    end
end

function BattleWnd:doFrameAction(action)
    local cmd = action.cmd;
    if cmd == battle_command.BATTLE_COMMAND_DEBUG then
        --1
    elseif cmd == battle_command.BATTLE_COMMAND_PLAYER_LEAVE then
        self:delPlayer(action.pos);
    elseif cmd == battle_command.BATTLE_COMMAND_FIRE then
        --3  服务器内部使用
    elseif cmd == battle_command.BATTLE_COMMAND_CHANGE_LAUNCH_ANGLE then
        self:otherPlayerOnFire(action.pos,cc.p(action.x,action.y));
    elseif cmd == battle_command.BATTLE_COMMAND_STOP_SHOOTING then
        --5
    elseif cmd == battle_command.BATTLE_COMMAND_CHANGE_LAUNCH_REATE then
        --6
    elseif cmd == battle_command.BATTLE_COMMAND_PLAYER_ENTER then
        local member = mgrs.data:getBattleData():getMemberByPos(action.pos);
        self:createPlayer(member.pos,member.idkey);
    elseif cmd == battle_command.BATTLE_COMMAND_HIT_TARGET then
        --8
    elseif cmd == battle_command.BATTLE_COMMAND_TARGET_DEATH then
        --9
    elseif cmd == battle_command.BATTLE_COMMAND_FISH_STOP then
        --10
    elseif cmd == battle_command.BATTLE_COMMAND_PAUSE then
        mgrs.data:getBattleData():battlePause();
    elseif cmd == battle_command.BATTLE_COMMAND_CONTINUE then
        mgrs.data:getBattleData():battleContinue();
    elseif cmd == battle_command.BATTLE_COMMAND_RESET then
        mgrs.data:getBattleData():battleReset();
    end
    mgrs.data:getBattleData():doFrameActionEnd(action);
end


function BattleWnd:setDebug(debug)
    local gezi = self:widget("middle.bgLayer.debugBg");
    local bg = self:widget("middle.bgLayer.bg");
    gezi:setVisible(debug);
    bg:setVisible(not debug);
    mgrs.res:loadImgTo(gezi,"ditugezi_5");
    local size = gezi:getContentSize();
    local rect = mgrs.wnd:getVisibleRect();
    gezi:setScaleX(rect.width/size.width);
    gezi:setScaleY(rect.height/size.height);
end

function BattleWnd:setSitePosition()
    local pos1 = mgrs.path:transGridToPos(mgrs.player:getCannonSite(1));
    local pos2 = mgrs.path:transGridToPos(mgrs.player:getCannonSite(2));
    local pos3 = mgrs.path:transGridToPos(mgrs.player:getCannonSite(3));
    local pos4 = mgrs.path:transGridToPos(mgrs.player:getCannonSite(4));
    local pos5 = mgrs.path:transGridToPos(mgrs.player:getCannonSite(5));
    local pos6 = mgrs.path:transGridToPos(mgrs.player:getCannonSite(6));
    self:widget("middle.cannonLayer.player1"):setPosition(pos1);
    self:widget("middle.cannonLayer.player2"):setPosition(pos2);
    self:widget("middle.cannonLayer.player3"):setPosition(pos3);
    self:widget("middle.cannonLayer.player4"):setPosition(pos4);
    self:widget("middle.cannonLayer.player5"):setPosition(pos5);
    self:widget("middle.cannonLayer.player6"):setPosition(pos6);
end

function BattleWnd:closeWnd()
    self:createClick({targetNode = self:widget("right.close")}):clickHandler(function()
        mgrs.wnd:closeWnd(enums.Wnd.Battle);
    end);
end

function BattleWnd:setTouchEvent()
    self.bulletLayer:setTouchEnabled(true);
    self.bulletLayer:addNodeEventListener(cc.NODE_TOUCH_EVENT, function (event)
	    if "began" == event.name then
            if(event.y >= 100) then
                self:tickOnFire(cc.p(event.x,event.y));
                self.scheduleLongClick = mgrs.scheduler:scheduleUpdateGlobal(handler(cc.p(event.x,event.y),handler(self,self.longClick)));
                return true;
            end
		    return false;
	    elseif "moved" == event.name then
            self:unscheduleLongClick();
            self:tickOnFire(cc.p(event.x,event.y));
            self.scheduleLongClick = mgrs.scheduler:scheduleUpdateGlobal(handler(cc.p(event.x,event.y),handler(self,self.longClick)));
	    elseif "ended" == event.name then
            self:unscheduleLongClick();
	    end
	end)
end

function BattleWnd:hint()
    for i=1,10 do
		mgrs.hint:showMarquee("发射子弹数量超过最大值  浴池中有大鱼啦！！！！！！！！");
		mgrs.hint:showMarquee("恭喜XXXXX捕获一条大金龙！！！！！！");
	end
    mgrs.behave:nextBehave(enums.Behave.Bulletin);
end

function BattleWnd:testAddFish()
    if true then
        local fishId = math.ceil( math.random(3,3) );
        local fish = self:createFish(fishId,13);
        --fish:setPosition(cc.p(300,300));
        --fish:updateCircleCenter();
        self.fishLayer:addChild(fish);
    end
end

function BattleWnd:tickOnFire(touchPoint)
    if self.isTickOnFire == false then
        self.isTickOnFire = true;
        self:onFire(mgrs.player:getMyChairId(),touchPoint);
        mgrs.scheduler:performWithDelayGlobal(function()
            self.isTickOnFire = false;
        end,0.2);
    end
end

function BattleWnd:longClick(point,dt)
    self.longClickTime = self.longClickTime + dt;
    if self.longClickTime >= 0.2 then
        self:tickOnFire(point);
    end
end

function BattleWnd:unscheduleLongClick()
    if self.scheduleLongClick then
        self.longClickTime = 0;
        mgrs.scheduler:unscheduleGlobal(self.scheduleLongClick);
        self.scheduleLongClick = nil;
    end
end

function BattleWnd:otherPlayerOnFire(chairId,grid)
    if chairId == mgrs.player:getMyChairId() then
        return;
    end
    local touchPoint = mgrs.path:transGridToPos(grid,pos);
    self:otherOnFire(chairId,touchPoint);
end

function BattleWnd:createPlayer(chairId,idKey)
    mgrs.log:printDebug("创建玩家 %d  当前帧率:%d",chairId,mgrs.data:getBattleData():getCurFrame())
    mgrs.input:unLock(enums.Locker.NoPlayerEnter);
    local cannon = self:clonePrefab("downCannon");
    cannon:setPosition(cc.p(0,0));
    local station = mgrs.player:getPlayerStation(chairId);
    if station == "player2" or station == "player3" or station == "player6"then
        cannon:setRotation(180);
        self:widget("num",cannon):setRotation(180);
    end
    local player = Player.new();
    cannon:setAnchorPoint(cc.p(0.5,0));
    player:setCannon(cannon);
    self:widget(station,self.cannonLayer):addChild(cannon);
    player:setChairId(chairId);
    player:setIdKey(idKey);
    mgrs.player:addPlayer(player,chairId);
    self:widget("num",cannon):setString(chairId);
end

function BattleWnd:delPlayer(chairId)
    mgrs.player:delPlayerByChairId(chairId);
    mgrs.data:getBattleData():playerExitRoom(chairId);
end

function BattleWnd:canOnFire()
    return true;
end

function BattleWnd:otherOnFire(chairId,touchPoint)
    local cannon = mgrs.player:getPlayer(chairId):getCannon();
    local cannonGuan = self:widget("gun",cannon);
    local station = mgrs.player:getPlayerStation(chairId);
    local startPoint = cc.p(self:widget(station,self.cannonLayer):getPosition());
    local angle = mgrs.math:getCannonAngle(startPoint,touchPoint);
    cannon:setRotation(angle);
    local x = 10 * math.sin(math.rad(angle));
    local y = 10 * math.cos(math.rad(angle));
    mgrs.action:beginAction(cannonGuan):MoveBy(0.05,cc.p(-x,-y)):CallFunc(function()
        self:createBullet(1,startPoint,touchPoint,chairId);
    end):MoveBy(0.1,cc.p(2*x,2*y)):MoveBy(0.05,cc.p(-x,-y)):Sequence(3):endAction();
end

function BattleWnd:onFire(chairId,touchPoint)
    --金币是否够
    if not self:canOnFire() then
        return;
    end
    --旋转炮台
    local cannon = mgrs.player:getPlayer(chairId):getCannon();
    local cannonGuan = self:widget("gun",cannon);
    --local worldX = cannonGuan:getParent():convertToWorldSpace(cc.p(cannonGuan:getPosition()));
    --local startPoint = self.bulletLayer:convertToNodeSpace(worldX);
    --local angle = mgrs.math:getCannonAngle(startPoint,touchPoint);
    --cannon:setRotation(angle);

    --放子弹
    --local onFire = self:widget("tmpStation",cannonGuan);
    --local worldX = onFire:getParent():convertToWorldSpace(cc.p(onFire:getPosition()));
    --local startPoint = self.bulletLayer:convertToNodeSpace(worldX);
    local station = mgrs.player:getPlayerStation(chairId);
    local startPoint = cc.p(self:widget(station,self.cannonLayer):getPosition());
    local angle = mgrs.math:getCannonAngle(startPoint,touchPoint);
    cannon:setRotation(angle);
    if mgrs.bullet:canAddBullet() then
        local x = 10 * math.sin(math.rad(angle));
        local y = 10 * math.cos(math.rad(angle));
        mgrs.action:beginAction(cannonGuan):MoveBy(0.05,cc.p(-x,-y)):CallFunc(function()
            self:createBullet(1,startPoint,touchPoint,chairId);
        end):MoveBy(0.1,cc.p(2*x,2*y)):MoveBy(0.05,cc.p(-x,-y)):Sequence(3):endAction();
    else
        mgrs.hint:showHint("发射子弹数量超过最大值");
        mgrs.behave:nextBehave(enums.Behave.Hint);
    end

    --存取开火信息 定时发送
    local a = math.rad(angle);
    local b = mgrs.path:transPosToGrid(touchPoint);
    local c = mgrs.data:getBattleData():getCurFrame();
    mgrs.proto:send({msgid = Protocol.C2A_ROLE_OPERATION,opType = operation_type.OPERATION_CHANG_LAUNCH_ANGLE,opParam = a,opParam2 = b,opParam3 = c})
end


function BattleWnd:createBullet(resId,startPoint,endPos,chairId)
    local bullet = Bullet.new(resId,startPoint,endPos);
    mgrs.bullet:addBullet(bullet,chairId);

    local station = mgrs.player:getPlayerStation(chairId);
    if station == "player1" or station == "player4" or station == "player5"then
        bullet:setPosition(cc.p(startPoint.x,startPoint.y + 1));
    else
        bullet:setPosition(cc.p(startPoint.x,startPoint.y - 1));
    end
    bullet:runActionToPoint();
    local bulletId = mgrs.player:getPlayer(chairId):getNewBulletId();
    bullet:setBulletId(bulletId);
    local pos = mgrs.player:getPlayer(chairId):initBulletlastpos();
    bullet:setBulletlastpos(pos);
    self.bulletLayer:addChild(bullet);
end

function BattleWnd:createFish(fishId,pathId)
    local fish = Fish.new(fishId,pathId);
    mgrs.fish:addFish(fish);
    return fish;
end

function BattleWnd:updateTest(dt)
    local x = math.random(0,1280);
    local y = math.random(100,720);
    --self:onFire(2,cc.p(x,y));

    local x = math.random(0,1280);
    local y = math.random(0,600);
    --self:onFire(3,cc.p(x,y));

    local x = math.random(0,1280);
    local y = math.random(0,600);
    --self:onFire(4,cc.p(x,y));

    
    local fishId = math.ceil( math.random(1,4) );
    local fishPath = math.ceil( math.random(1,10));
    local fish = self:createFish(fishId,fishPath);
    self.fishLayer:addChild(fish);
end


function BattleWnd:updateFish(dt)
    mgrs.fish:update(dt);
end

function BattleWnd:updateBullet(dt)
    mgrs.bullet:update(dt);
end

function BattleWnd:onClose()
    mgrs.player:reset();
    mgrs.fish:reset();
    mgrs.bullet:reset();
    mgrs.scheduler:unscheduleGlobal(self.scheduleFish);
    mgrs.scheduler:unscheduleGlobal(self.scheduleBullet);
    --mgrs.scheduler:unscheduleGlobal(self.scheduleTest);
    --离开战斗场景
    mgrs.proto:send({msgid = Protocol.C2A_ROLE_OPERATION,opType = operation_type.OPERATION_BATTLE_LEAVE,opParam = 1});
end

function BattleWnd:btnClicked()
    mgrs.log:printDebug("!!!!!TestWnd onClose!!!!!");
end



function BattleWnd:reqData(handler)
	handler(true);	
end



function BattleWnd:getLayer()
	return enums.Layer.Window;
end

function BattleWnd:getPreloadResList()
	return {
        Spine = {"zhidan_01","fish_01","fish_02","fish_03","fish_04","fish_17","fish_18"}
    };
end

function BattleWnd:getExclusiveType()
	return 0;
end

function BattleWnd:isOpenCloseSoundEnabled()
	return false;
end

function BattleWnd:onEnter()
	mgrs.log:printFuncCall();
end
function BattleWnd:onExit()
	mgrs.log:printFuncCall();
end
function BattleWnd:onEnterTransitionFinish()
	mgrs.log:printFuncCall();
end

function BattleWnd:onExitTransitionStart()
	mgrs.log:printFuncCall();
end


mgrs.wnd:registerWnd(enums.Wnd.Battle,BattleWnd);

--endregion
